package com.wisdom.benefit.jufa.net;

import android.util.Log;

import com.wisdom.benefit.jufa.base.BaseApplication;
import com.wisdom.benefit.jufa.net.interceptor.LoggerInterceptor;
import com.wisdom.benefit.jufa.utils.CommonUtils;

import java.io.File;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitService {

    private static final String TAG = RetrofitService.class.getSimpleName();
    private static final long CACHE_SIZE = 1024 * 1024 * 100;//100M
    //半正式
//    private static String ONLINE_URL = "http://122.10.18.183:8081";
//    private static String ONLINE_URL = "http://192.168.2.127:8081";
//    private static String ONLINE_URL = "http://192.168.1.123:8081";

    //正式环境
    private static String ONLINE_URL = "http://www.tangchaopay.net:8081";
    //3.7测试
//    private static String ONLINE_URL = "http://www.tangchaopay.cn:8081";
    //线上
//    private static String ONLINE_URL = "http://120.76.140.128:8081";
    //测试
//    private static String ONLINE_URL = "http://192.168.0.104:8081";
    public static String BASE_URL = ONLINE_URL;
    public static final String BASE_URL_DIR = "v2";
    private static ApiService mApiService;
    private static final long DEFAULT_CONNECT_TIME_OUT = 120L;
    private static final long DEFAULT_WRITE_TIME_OUT = 120L;
    private static final long DEFAULT_READ_TIME_OUT = 120L;
    private static final String METHOD_POST = "post";
    private static final String FORM_URLENCODED = "application/x-www-form-urlencoded";

    /**
     * 获取带缓存的网络加载器
     * 缓存策略：
     * 1.没有网络，强制用缓存.
     * 2.有网络，设置缓存期限一天，但是会去服务器请求最新的数据.
     *
     * @return 网络加载器.
     */
    public static ApiService getNetService() {
        if (mApiService == null) {
            synchronized (RetrofitService.class) {
                if (mApiService == null) {
                    Cache cache = new Cache(new File(BaseApplication.getContext().getCacheDir(), "NetCache"), CACHE_SIZE);
                    OkHttpClient okHttpClient = new OkHttpClient().newBuilder().cache(cache)
                            .retryOnConnectionFailure(true)
                            .addInterceptor(sCommonInterceptor)
                            .addInterceptor(sRewriteCacheControlInterceptor)
                            .addNetworkInterceptor(new LoggerInterceptor(LoggerInterceptor.TAG, true))
                            .connectTimeout(DEFAULT_CONNECT_TIME_OUT, TimeUnit.SECONDS)
                            .writeTimeout(DEFAULT_WRITE_TIME_OUT, TimeUnit.SECONDS)
                            .readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
                            .build();

                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .client(okHttpClient)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                            .build();

                    mApiService = retrofit.create(ApiService.class);
                }
            }
        }

        return mApiService;
    }

    /**
     * 封装公共参数
     */
    private static final Interceptor sCommonInterceptor = chain -> {
        Request oldRequest = chain.request();

        //header添加token
        Request.Builder requestBuilder = oldRequest.newBuilder()
                .addHeader("token", BaseApplication.getContext().getToken());

        Request newRequest;
        if (oldRequest.method().equalsIgnoreCase(METHOD_POST)) {
            RequestBody requestBody = oldRequest.body();
            if (requestBody != null && requestBody.contentType() != null
                    && Objects.requireNonNull(requestBody.contentType()).toString().equalsIgnoreCase(FORM_URLENCODED)) {
                FormBody oldFormBody = (FormBody) oldRequest.body();
                FormBody.Builder formBodyBuilder = new FormBody.Builder();
                if (oldFormBody != null) {
                    for (int i = 0; i < oldFormBody.size(); i++) {
                        if (!"token".equals(oldFormBody.name(i)))//过滤掉token
                            formBodyBuilder.add(oldFormBody.name(i), oldFormBody.value(i));
                    }
                }
                formBodyBuilder.add("timestamp", System.currentTimeMillis() + "");//添加timestamp
                newRequest = requestBuilder.method(oldRequest.method(), formBodyBuilder.build()).build();
            } else {
                newRequest = requestBuilder.build();
            }
        } else {
            newRequest = requestBuilder.build();
        }

        return chain.proceed(newRequest);
    };

    /**
     * 云端响应头拦截器，用来配置无网络时缓存的请求
     * Dangerous interceptor that rewrites the server's cache-control header.
     */
    private static final Interceptor sRewriteCacheControlInterceptor = chain -> {
        Request request = chain.request();
        if (!CommonUtils.isNetworkAvailable(BaseApplication.getContext())) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            Log.e(TAG, "no network");
        }

        return chain.proceed(request);
    };
}
